/* =============================================================
 * Your Grandmother's guide to Algorithms
 * =============================================================
 *
 * Copyright (c) 2007, Saverio Miroddi
 *
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without 
 * modification, are permitted provided that the following conditions are met:
 * 
 *     * Redistributions of source code must retain the above copyright notice,
 *       this list of conditions and the following disclaimer.
 *     * Redistributions in binary form must reproduce the above copyright 
 *       notice, this list of conditions and the following disclaimer in the 
 *       documentation and/or other materials provided with the distribution.
 *     * Neither the name of the SaverioMiroddiSoftware nor the names of its 
 *       contributors may be used to endorse or promote products derived from 
 *       this software without specific prior written permission.
 * 
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
 * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER 
 * OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
 * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
 * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
 * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
 * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
 * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 *  
 * ---------------------------
 * TreePanel.java
 * ---------------------------
 *
 */
package treegui;

import java.awt.Dimension;
import java.awt.Point;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.atomic.AtomicBoolean;

import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;

import btree.BTree;

import treegui.graphlibwrappers.AbsTreeComponent;
import treegui.graphlibwrappers.JGraphTreeComponent;
import treegui.nodewrappers.GuiBTreeNode;
import treegui.nodewrappers.IGuiNode;

/**
 * TODO: mistakenly shows "auto-links" if if more nodes are equal(). 
 * 
 * @author Saverio Miroddi
 */
public class TreePanel extends JPanel 
{
	public static final int DEFAULT_WIDTH = 1024;
	public static final int DEFAULT_HEIGHT = 600;
	public static final int OFS_X = -50;
	public static final int OFS_Y = -50;
	
	public TreePanel(IGuiNode tree, int x, int y, int xofs, int yofs)
	{
		List<IGuiNode> treeData = getPositionedNodes(tree, x, y);
		
		AbsTreeComponent treeComp = 
			new JGraphTreeComponent(treeData, new Dimension(xofs, yofs));
		JComponent treeComponent = treeComp.getGraphComponent();

		add(treeComponent);
	}
	
	private List<IGuiNode> getPositionedNodes(
			IGuiNode tree, int xsize, int ysize)
	{
		/* Create a list with all the nodes */
		
		/** Every internal list is a level */
		List<List<IGuiNode>> allNodes = new ArrayList<List<IGuiNode>>();
		
		List<IGuiNode> currentLevelNodes = new ArrayList<IGuiNode>();
		currentLevelNodes.add(tree);
		
		while (currentLevelNodes.size() > 0) {
			allNodes.add(currentLevelNodes);
			
			List<IGuiNode> nextLevelNodes = new ArrayList<IGuiNode>();
			
			for (IGuiNode node : currentLevelNodes) {
				for (IGuiNode child : node.getChildren()) {
					nextLevelNodes.add(child);
				}
			}
			
			currentLevelNodes = nextLevelNodes;
		}
		
		/** Set positions */
		
		final double blockYSize = (double)ysize / allNodes.size(); 
		
		for (int rowIdx = 0; rowIdx < allNodes.size(); rowIdx++) {
			int columnsNum = allNodes.get(rowIdx).size();
			
			// 0.5 -> position in the middle of the block
			int rowPos = (int)(blockYSize * (rowIdx + 0.5));
						
			double blockXSize = (double)xsize / columnsNum;
			
			for (int colIdx = 0; colIdx < columnsNum; colIdx++) {
				int colPos = (int)(blockXSize * (colIdx + 0.5));
				
				Point position = new Point(colPos, rowPos);
				allNodes.get(rowIdx).get(colIdx).setPosition(position);
			}
		}
		
		/* Create plain list */
		
		List<IGuiNode> plainList = new ArrayList<IGuiNode>();
		
		for (List<IGuiNode> level : allNodes) {
			plainList.addAll(level);
		}
		
		return plainList;
	}

	public static void showInFrame(
			IGuiNode tree)
	{
		showInFrame(tree, DEFAULT_WIDTH, DEFAULT_HEIGHT, OFS_X, OFS_Y);
	}
	
	public static void showInFrame(
			BTree tree)
	{
		showInFrame(new GuiBTreeNode(tree.getRootNode()));
	}
	
	public static void showInFrame(
			IGuiNode tree, int screenWidth, int screenHeight,
			int xofs, int yofs)
	{
		JPanel treePanel = new TreePanel(tree, screenWidth, screenHeight, xofs, yofs);

		JFrame frame = new JFrame();
		frame.getContentPane().add(new JScrollPane(treePanel));
		frame.pack();
		frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
		
		showAndWait(frame);
	}

	private static void showAndWait(final JFrame frame) {
		// ;-) so we don't use a member var 
		final AtomicBoolean windowClosed = new AtomicBoolean(false);
		
		frame.addWindowListener(new WindowAdapter() {
			@Override
			public void windowClosed(WindowEvent we) {
				synchronized(frame) {
					windowClosed.set(true);
					frame.notify(); 
				}
			}
		});

		frame.setVisible(true);
		
		synchronized(frame) {
			while (! windowClosed.get()) {
				try {
					frame.wait();
				} catch (InterruptedException e) { /* slurp! */ }
			}
		}
	}
}
